/* 
* Copyright (c) 2009, The University of Texas at Austin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, 
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation and/or other materials 
* provided with the distribution.
*
* Neither the name of The University of Texas at Austin nor the names of its contributors may be 
* used to endorse or promote products derived from this software without specific prior written 
* permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Bio.Data.Providers;
using Bio.Data.Providers.Interfaces;
using BioBrowser.Models;
using JulMar.Windows;
using JulMar.Windows.Mvvm;
using Microsoft.Win32;

namespace BioBrowser.ViewModels
{
    /// <summary>
    /// This is the top-level category in our window
    /// </summary>
    public class BioCategoryViewModel : SelectionViewModel
    {
        public IEnumerable<IBioDataProvider> FormatLoaders { get; set; }
        public MTObservableCollection<OpenBioDataViewModel> Children { get; private set; }
        public ICommand DefaultCommand { get; private set; }

        /// <summary>
        /// Constructor for the BioCategory
        /// </summary>
        public BioCategoryViewModel()
        {
            DefaultCommand = new DelegatingCommand(OnOpenDefaultFile);
            Children = new MTObservableCollection<OpenBioDataViewModel>();
        }

        private void OnOpenDefaultFile()
        {
            var loader = FormatLoaders.FirstOrDefault();
            if (loader != null)
                LoadFromFormat(loader);
        }

        /// <summary>
        /// This populates the context menu for the category
        /// </summary>
        public override List<MenuItem> MenuOptions
        {
            get
            {
                IsSelected = true;

                var menu = new List<MenuItem>();
                if (FormatLoaders.Count() > 0)
                {
                    var mi = new MenuItem("O_pen");
                    foreach (var fl in FormatLoaders)
                    {
                        var currentLoader = fl;
                        mi.Children.Add(new MenuItem(fl.Description) { ImageUri = fl.ImageUrl, Command = new DelegatingCommand(() => LoadFromFormat(currentLoader)) });
                    }

                    menu.Add(mi);
                }

                menu.Add(new MenuItem("Close _All") { Command = new DelegatingCommand(OnCloseAll, () => Children.Count > 0)});

                return menu;
            }
        }

        /// <summary>
        /// This loads a specific BioFormat
        /// </summary>
        /// <param name="entry"></param>
        private void LoadFromFormat(IBioDataProvider entry)
        {
            string filter = entry.FileFilter, filename = null;
            if (!string.IsNullOrEmpty(filter))
            {
                OpenFileDialog ofd = new OpenFileDialog {Filter = filter};
                if (ofd.ShowDialog().Value)
                {
                    filename = ofd.FileName;
                }
                else
                    return;
            }

            BioFormatType format = entry.SupportedTypes;
            IBioDataLoader dataLoader = entry.Create(filename);

            if (dataLoader != null)
            {
                var dvm = new OpenBioDataViewModel(filename, format, dataLoader, entry);
                dvm.Load();
                dvm.CloseRequest += OnDataFileClosing;

                Children.Add(dvm);
                IsExpanded = true;
            }
        }

        void OnDataFileClosing(object sender, EventArgs e)
        {
            var dvm = sender as OpenBioDataViewModel;
            if (dvm != null)
            {
                dvm.CloseRequest -= OnDataFileClosing;
                Children.Remove(dvm);
            }
        }

        /// <summary>
        /// This closes all the open bio formats
        /// </summary>
        private void OnCloseAll()
        {
            var childCopy = new List<OpenBioDataViewModel>(Children);
            foreach (var child in childCopy)
                child.CloseCommand.Execute(null);   
        }
    }
}